package com.dynamictpm.client;

import com.dynamictpm.build.ThreadFactoryBuilder;
import com.dynamictpm.remote.HttpAgent;
import org.springframework.beans.factory.DisposableBean;

import java.util.concurrent.*;

/**
 * -----------------------------
 * PackageName： com.dynamictpm.client
 * ClassName：ClientWorker
 * Description：客户端连接处理类
 *
 * @author：it-yml CreateTime：2023-07-02
 * -----------------------------
 */
public class ClientWorker implements DisposableBean {
    private final ScheduledExecutorService executorService;

    private final HttpAgent httpAgent;

    public ClientWorker(HttpAgent httpAgent){
        this.httpAgent = httpAgent;


        this.executorService = Executors.newSingleThreadScheduledExecutor(
                ThreadFactoryBuilder.builder().prefix("client.long.polling.executor").daemon(Boolean.TRUE).build()
        );
        // 创建一个线程池，只有一个守护线程
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1, runnable -> {
            Thread thread = new Thread(runnable);
            thread.setName("client.worker.executor");
            thread.setDaemon(true);
            return thread;
        });

        // 定时调度，第一次延迟1毫秒，后续每10 毫秒 调度一次
        executor.schedule(()->{
            executorService.execute(new LongPollingRunnable(executorService));
        },1L, TimeUnit.MILLISECONDS);

    }


    @Override
    public void destroy() throws Exception {
        executorService.shutdownNow();
    }
}
